package com.vertx.web.bean;

import com.vertx.core.annotation.base.MethodAnnotationExplain;
import com.vertx.core.beam.AbstractBeanFactory;
import com.vertx.core.beam.BeanContainer;
import com.vertx.web.explain.RestApiAnnotationExplain;
import io.vertx.core.Vertx;
import io.vertx.ext.web.Router;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 描述: VertxBeanFactory
 * 创建人:hzw
 * 创建时间: 2018/4/17 16:42
 **/
public class VertxBeanFactory extends AbstractBeanFactory{

    private Router router;

    private Vertx vertx;

    public VertxBeanFactory(Router router,Vertx vertx,String[] scanPackage) {
        super(scanPackage);
        this.vertx = vertx;
        this.router = router;
        loadAnnotationExplain();
    }

    @Override
    protected void setMethod(BeanContainer beanContainer) throws Exception {
        Method[] methods = beanContainer.getBeanClass().getMethods();//方法必需是public
        for (Method method : methods) {
            for (Annotation annotation : method.getAnnotations()) {
                if (annotationExplainContainer.containsKey(annotation.annotationType())) {
                    MethodAnnotationExplain explain = (MethodAnnotationExplain) annotationExplainContainer.get(annotation.annotationType());
                    Router subRouter = Router.router(vertx);
                    router.mountSubRouter("/", subRouter);
                    explain.handler(beanContainer, method, annotation, this, new Object[]{subRouter,vertx});
                }
            }
        }
    }

    private void loadAnnotationExplain() {
        try {
            registerAnnotationExplain(RestApiAnnotationExplain.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
